package com.NetSunWeiQin.chapter06.fileSever;

import java.net.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileClient {
    private String urlAddress = "myftp://localhost:8000";
    private String filename = "demofile.txt";
    FileURLConnection connection;

    public FileClient() {
    }

    public void talk() {
        try {

            URL.setURLStreamHandlerFactory(new FileURLStreamHandlerFactory());

            URLConnection.setContentHandlerFactory(new FileContentHandlerFactory());
            URL url = new URL(urlAddress);
            connection = (FileURLConnection) url.openConnection();
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

            System.out.println(" 获取数据流");
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));

            String msg = null;
            while ((msg = localReader.readLine()) != null) {

                if (msg.equals("bye")) {
                    byte[] byesmsg = msg.getBytes();
                    outputStream.writeInt(byesmsg.length);
                    outputStream.write(byesmsg);
                    break;
                }

                if (msg.equals("get")) {
                    getFile(filename);
                }

                if (msg.equals("put")) {
                    putFile(filename);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null)
                    connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void putFile(String fName) throws IOException {
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        String filename = fName;
        java.io.File file = new java.io.File("client//" + filename);

        if (!file.exists()) {
            System.out.println("客户端获取文件:" + filename + "");
            return;
        } else {
            String msg = "put" + " " + filename + " " + file.length();
            byte[] msgbytes = msg.getBytes(StandardCharsets.UTF_8);
            outputStream.writeInt(msgbytes.length);
            outputStream.write(msgbytes);
        }

        FileInputStream fInputStream = new FileInputStream("client//" + filename);

        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = fInputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        fInputStream.close();
        System.out.println(">获取的文件名:" + filename + " ");
        System.out.println();
    }

    private void getFile(String fName) throws IOException {

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        byte[] msgbytes = ("get" + " " + filename).getBytes();
        outputStream.writeInt(msgbytes.length);
        outputStream.write(msgbytes);

        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        int msglen = inputStream.readInt();
        if (msglen == 0) {
            System.out.println(">获取的文件名:" + filename + " ");
            return;
        }
        byte[] buffer = new byte[msglen];
        inputStream.read(buffer);
        String msg = new String(buffer);

        if (!msg.contains("ok")) {
            throw new IOException("IOException");
        }

        String filename = fName;
        int length = getFileLenFromMsg(msg);
        String path = "client//" + filename;


        FileOutputStream fileOut = new FileOutputStream(path);
        byte[] buff = new byte[1024];
        int m = length / buff.length;
        int n = length % buff.length;
        int len = 0;
        for (int i = 0; i < m + 1; i++) {
            if (i == m) {
                len = inputStream.read(buff, 0, n);
                fileOut.write(buff, 0, len);
            } else {
                len = inputStream.read(buff);
                fileOut.write(buff, 0, len);
            }
        }

        fileOut.close();
        System.out.println(">获取的文件名:" + filename + " ");
        System.out.println();
    }

    private int getFileLenFromMsg(String msg) {
        String[] arrays = msg.split(":");
        return Integer.parseInt(arrays[1]);
    }

    public static void main(String args[]) throws IOException {
        new FileClient().talk();
    }

}

